package com.itcast.activiti.utils;

import com.alibaba.fastjson.JSON;
import com.itcast.activiti.domain.Menu;

import java.util.ArrayList;
import java.util.List;

public class MenuTree {
	private List<Menu> menuList = new ArrayList<>();
	private List<Integer> permissionIdList = new ArrayList<>();

	public MenuTree(List<Menu> menuList, List<Integer> permissionIdList) {
		this.menuList = menuList;
		this.permissionIdList = permissionIdList;
	}

	//建立树形结构
	public List<Menu> builTree() {
		List<Menu> treeMenus = new ArrayList<>();
		for (Menu menuNode : getRootNode()) {
			menuNode = buildChilTree(menuNode);
			menuNode.setSelected(permissionIdList == null ? false : permissionIdList.contains(menuNode.getId()));
			treeMenus.add(menuNode);
		}
		return treeMenus;
	}

	//递归，建立子树形结构
	private Menu buildChilTree(Menu pNode) {
		List<Menu> chilMenus = new ArrayList<>();
		for (Menu menuNode : menuList) {
			if (menuNode.getParentId().equals(pNode.getId())) {
				menuNode.setSelected(permissionIdList == null ? false : permissionIdList.contains(menuNode.getId()));
				chilMenus.add(buildChilTree(menuNode));
			}
		}
		pNode.setChildren(chilMenus.size() == 0 ? null : chilMenus);
		return pNode;
	}

	//获取根节点
	private List<Menu> getRootNode() {
		List<Menu> rootMenuLists = new ArrayList<>();
		for (Menu menuNode : menuList) {
			if (menuNode.getParentId() == 0) {
				rootMenuLists.add(menuNode);
			}
		}
		return rootMenuLists;
	}

	public static void main(String[] args) {
		List<Menu> menuList = new ArrayList<>();
		List<Integer> permissionIdList = new ArrayList<>();
		permissionIdList.add(1001);
		permissionIdList.add(1002);
		menuList.add(new Menu(1001, 0, "系统管理"));
		menuList.add(new Menu(1002, 1001, "系统管理-权限管理"));
		menuList.add(new Menu(1003, 1002, "系统管理-权限管理-用户"));
		menuList.add(new Menu(1004, 1003, "系统管理-权限管理-新加用户-系统监控"));
		MenuTree menuTree = new MenuTree(menuList, permissionIdList);
		menuList = menuTree.builTree();
		String jsonOutput = JSON.toJSONString(menuList);
		System.out.println(jsonOutput);
	}
}
